# configure-dhcpd.pm
# Copyright (C) 2006,2007  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

#
# For more information: http://carrierclass.net/
#
use strict; use warnings;

package CCNv2::Provision::Application::dhcpd;
use base qw(CCNv2::Provision::Application::dhcpd);

sub anchor_system()
{
    my $self = shift;

    my $dhcpconf = '';
    
    $self->sql_do_for( <<'SQL', $self->p->server_pk,
        SELECT pool FROM pool_server WHERE server = ? AND role = 'dhcp';
SQL
    sub
    {
        my $POOL = shift;
        my @file_servers = 
            $self->sql_get_array(q(SELECT server FROM pool_server WHERE pool_pk = ? AND role = 'file'),$POOL);
        $self->error("You must select a file server for pool $POOL"), return
            if $#file_servers < 0;

        # TBD Pick one instead of the first one..
        my $FILE_SERVER = primary_ip($file_servers[0]);

        my @dns_servers = 
            $self->sql_get_array(q(SELECT server FROM pool_server WHERE pool = ? AND role = 'file'), $POOL);

        return $self->error("You must select a dns server for pool $POOL")
            if $#dns_servers < 0;
        my $DNS_SERVER = join(' ', map { primary_ip($_) } @dns_servers);

        $dhcpconf .= <<"EOT";
# Pool ${POOL}
group {
    option domain-name-servers ${DNS_SERVER};
    option tftp-server-name    "${FILE_SERVER}";
    # option bootfile-name "..."
    # filename "..."
    next-server         ${FILE_SERVER};
EOT

        $self->sql_do_for( <<'SQL', $POOL,
            SELECT mac FROM phone WHERE pool = ?;
SQL
        sub
        {
            my $MAC   = CCN::Text::mac_from_dotted(shift);
            my $HWMAC = CCN::Text::mac_to_dotted($MAC);

            $dhcpconf .= <<"EOT";
    host phone${MAC} { hardware ethernet ${HWMAC}; }
EOT
        }); # for MAC

        $dhcpconf .= <<"EOT";
}
# End pool ${POOL}
EOT
    }); # for POOL
    
    return $dhcpconf;
}

1;